import { SkerFloaty } from "./float"
import { homeFollowSearch } from "./homeFollowSearch"
import { homeLiveLiveSearch } from "./homeLiveLiveSearch"
import { hourTop } from "./hourTop/hourTop"
import { SkerInfo } from "./info"
import { taskQb } from "./taskQb"
import { taskZb } from "./taskZb"
import { taskZbWatch } from "./taskZbWatch"
import { Pages } from "./to/pages/Pages"
import { router } from "./to/pages/routerVisitor"
import { currentPage } from "./to/pages/utils/consts"
import { toHomeFollow } from "./to/toHomeFollow"
import { toHomeLiveLive } from "./to/toHomeLive"
import { getCurrentPackageName } from "./utils/getCurrentPackageName"
import { httpPost } from "./utils/httpPost"
import { getMaxFail, setMaxFail } from "./utils/maxFail"
import { pullDownToRefresh, swipeUp } from "./utils/pullDownToRefresh"
import { useSetting } from "./utils/useSetting"
import { useStorage } from "./utils/useStorage"
setInterval(() => { }, 1000)

function bootstrap() {
    if (floaty.checkPermission()) {
        SkerFloaty.createFloaty()
        SkerInfo.init()
    } else {
        floaty.requestPermission()
        engines.stopAll()
        return
    }
    requestScreenCapture()

    device.keepScreenOn()
    let t: AutoJs.Thread | undefined = undefined
    let start = false;
    const storage = useStorage()
    let preStatus: string = ``
    const checkStatus = () => {
        try {
            const status = httpPost('kwai/checkStatus', {})
            if (status && status.status) {
                if (status.status !== preStatus) {
                    events.emit(`start`, status.status === `start`)
                }
            }
        } catch (e) { }
    }
    const t2 = setInterval(() => checkStatus(), random(2000, 10000))
    checkStatus();
    events.on('exit', () => {
        start = false;
        storage.put(`start`, start)
        clearInterval(t2)
    })

    events.on('start', (isStart: boolean) => {
        if (isStart) {
            start = true;
            preStatus = `start`
            storage.put(`start`, start)
            t = threads.start(() => {
                events.emit('log', "已启动")
                const setting = useSetting()
                switch (setting.category) {
                    case '抓包':
                        taskZb()
                        break;
                    case '抢包':
                        break;
                    case '监控':
                        taskZbWatch()
                        break;
                }
                events.emit('stop', true)
            })
            t.waitFor()
        } else {
            start = false;
            preStatus = `stop`
            storage.put(`start`, start)
            if (t && t.isAlive()) {
                t.interrupt()
            }
            t = undefined
            events.emit('stop', true)
            events.emit('log', "已停止")
        }
    })
}

try {
    bootstrap()
} catch (e) {
    console.error(e)
}
